<script setup lang="ts">
import { ref } from "vue";

import { ElMessage, ElMessageBox } from "element-plus";
import { getToken, formatToken } from "@/utils/auth";
import type { UploadProps, UploadUserFile } from "element-plus";
import { message } from "@/utils/message";
const fileList = ref<UploadUserFile[]>([
  {
    name: "element-plus-logo.svg",
    url: "https://element-plus.org/images/element-plus-logo.svg"
  },
  {
    name: "element-plus-logo2.svg",
    url: "https://element-plus.org/images/element-plus-logo.svg"
  }
]);

const handleRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  console.log(file, uploadFiles);
};

const handlePreview: UploadProps["onPreview"] = uploadFile => {
  console.log(uploadFile);
};

const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 3, you selected ${files.length} files this time, add up to ${
      files.length + uploadFiles.length
    } totally`
  );
};
const beforeRemove: UploadProps["beforeRemove"] = (
  uploadFile,
  _uploadFiles
) => {
  return ElMessageBox.confirm(
    `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  );
};

const beforeUpload: UploadProps["beforeUpload"] = uploadFile => {
  if (uploadFile.size > 104857600) {
    message("文件超出大小限制", { customClass: "el", type: "error" });
    return false;
  }
};

const headers = () => {
  const data = getToken();
  return { Authorization: formatToken(data.accessToken) };
};
</script>

<template>
  <el-upload
    v-model:file-list="fileList"
    class="upload-demo"
    action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
    :headers="headers"
    :multiple="false"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :before-remove="beforeRemove"
    :limit="3"
    :on-exceed="handleExceed"
    :before-upload="beforeUpload"
  >
    <el-button type="primary">选择上传文件</el-button>
    <template #tip>
      <div class="el-upload__tip">文件限制大小 100MB .</div>
    </template>
  </el-upload>
</template>
